<template>
  <div class="warehouse-add-container">
    <el-card class="base-info-card">
      <template #header>
        <span class="card-header-title">基础信息</span>
      </template>
      <el-form :model="addForm" ref="addFormRef" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库编号">
              <div style="display: flex; align-items: center;">
              <el-input placeholder="自动获取系统编号" disabled style="margin-right: 35px; flex: 1;" />
              <el-checkbox v-model="addForm.is_default" label="默认仓库" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库名称" prop="wh_name">
              <el-input v-model="addForm.wh_name" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库容量/m³" prop="wh_capacity">
              <el-input v-model="addForm.wh_capacity" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库管部门" prop="wh_depId">
              <el-select 
                v-model="addForm.wh_depId" 
                placeholder="请选择"
                style="width: 100%"
                @change="handleDepartmentChange"
              >
                <el-option 
                  v-for="dept in departmentOptions"
                  :key="dept.department_id"
                  :label="dept.department_name"
                  :value="dept.department_id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库主管" prop="wh_userId">
              <el-select 
                v-model="addForm.wh_userId" 
                placeholder="请选择"
                @change="handleUserChange"
                filterable
                clearable
              >
                <el-option 
                  v-for="user in userOptions"
                  :key="user.user_id"
                  :label="user.user_name"
                  :value="user.user_id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="wh_userPhone">
              <el-input v-model="addForm.wh_userPhone" placeholder="选择主管后自动获取" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="仓库地址" prop="wh_address">
          <el-input v-model="addForm.wh_address" placeholder="请输入" />
        </el-form-item>
        
        <el-form-item label="仓库状态" prop="wh_status">
          <el-radio-group v-model="addForm.wh_status">
            <el-radio :label="0">启用</el-radio>
            <el-radio :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="仓库锁定" prop="is_locked">
          <el-switch v-model="addForm.is_locked" />
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input v-model="addForm.remark" type="textarea" placeholder="请输入" />
        </el-form-item>
       
      </el-form>
    </el-card>
  </div>

  <div class="location-table-container">
    <el-card class="base-info-card">
      <template #header>
        <span class="card-header-title">库位信息</span>
      </template>
      <div style="text-align: left; margin-bottom: 15px;">  
        <el-button type="success" @click="drawer = true">添加</el-button>
        <el-button @click="handleBatchDelete">删除</el-button>
        <el-upload
                ref="importUpload"
                style="display: inline-block; margin-left: 10px;"
                :auto-upload="false"
                :on-change="handleFileChange"
                :show-file-list="false"
                accept=".xlsx,.xls"
            >
                <el-button :loading="importLoading">导入</el-button>  
            </el-upload>
            <el-button @click="Export"  style="margin-left: 10px;">导出</el-button>
      </div>
      
      <!-- 表格 -->
      <el-table 
        :data="slotdata" 
        style="width: 100%" 
        @selection-change="SelectChange"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        
      >
        <el-table-column type="selection"></el-table-column>
        <el-table-column prop="slot_id" label="序号" width="80"></el-table-column>
        <el-table-column prop="slot_code" label="库位编号" width="135"></el-table-column>
        <el-table-column prop="slot_name" label="库位名称" width="150"></el-table-column>
        <el-table-column prop="slot_capacity" label="库位容量/m³" width="120"></el-table-column>
        <el-table-column prop="slot_userName" label="仓库主管" width="150"></el-table-column>
        <el-table-column prop="slot_status" label="库位状态" width="100" :formatter="formatStatus"></el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150"></el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button type="success" size="small" text @click="showEditDrawer(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" text @click="ShowDelete(scope.row.slot_code)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
     <!-- 页码 -->
        <el-pagination 
            :page-size="pagination.pageSize" 
            :pager-count="11" 
            layout="prev, pager, next, jumper" 
            :total="pagination.total"
            v-model:current-page="pagination.currentPage"
            @current-change="handlePageChange" 
            style="float:right;margin-top:20px">
        </el-pagination>

    </el-card>
  </div>



  <!--添加抽屉-->
    <el-drawer v-model="drawer" title="新增" size="30%">
    <el-form :model="addform" ref="addformref" :rules="slotRules" label-width="auto"  >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="库位编号" prop="slot_code">
            <el-input v-model="addform.slot_code" placeholder="自动获取系统编号" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="库位名称" prop="slot_name">
            <el-input v-model="addform.slot_name" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="库位容量/m³" prop="slot_capacity" >
            <el-input v-model="addform.slot_capacity" placeholder="请输入" />
          </el-form-item>
        </el-col>
       <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="库位主管" prop="slot_userId">
          <el-select 
            v-model="addform.slot_userId" 
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option 
              v-for="user in userOptions"
              :key="user.user_id"
              :label="user.user_name"
              :value="user.user_id"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="库位状态" prop="slot_status">
          <el-radio-group v-model="addform.slot_status">
            <el-radio :label="0">启用</el-radio>
            <el-radio :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
    </el-row>
        <el-col :span="12">
          <el-form-item label="排序" prop="slot_sort">
            <el-input v-model="addform.slot_sort" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="备注" prop="remark">
        <el-input v-model="addform.remark" type="textarea" placeholder="请输入" />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div style="flex: auto; text-align: right;">
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" @click="Add">保存</el-button>
      </div>
    </template>
  </el-drawer>

  <!-- 编辑抽屉 -->
<el-drawer v-model="editDrawer" title="编辑" size="30%">
  <el-form :model="editForm" ref="editFormRef" :rules="slotRules" label-width="120px" label-position="left">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="库位编号" prop="slot_code">
          <el-input v-model="editForm.slot_code" placeholder="自动获取系统编号" disabled />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="库位名称" prop="slot_name">
          <el-input v-model="editForm.slot_name" placeholder="请输入" />
        </el-form-item>
      </el-col>
    </el-row>
    
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="库位容量/m³" prop="slot_capacity">
          <el-input v-model="editForm.slot_capacity" placeholder="请输入" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="库位主管" prop="slot_userId">
          <el-select 
            v-model="editForm.slot_userId" 
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option 
              v-for="user in userOptions"
              :key="user.user_id"
              :label="user.user_name"
              :value="user.user_id"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="库位状态" prop="slot_status">
          <el-radio-group v-model="editForm.slot_status">
            <el-radio :label="0">启用</el-radio>
            <el-radio :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="排序" prop="slot_sort">
          <el-input v-model="editForm.slot_sort" placeholder="请输入" />
        </el-form-item>
      </el-col>
    </el-row>
    
    <el-form-item label="备注" prop="remark">
      <el-input v-model="editForm.remark" type="textarea" placeholder="请输入" />
    </el-form-item>
  </el-form>
  
  <template #footer>
    <div style="flex: auto; text-align: right;">
      <el-button @click="editDrawer = false">取消</el-button>
      <el-button type="primary" @click="Update">保存</el-button>
    </div>
  </template>
</el-drawer>

   <!--删除模态框-->
    <el-dialog v-model="DeleteialogVisible" width="400" style="text-align: left;"  align-center>
        <span>确定删除吗?</span>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-on:click="DeleteialogVisible = false">取消</el-button>
                <el-button type="primary" @click="Delete()">确定</el-button>
            </div>
        </template>
    </el-dialog>
        
 
   <!-- 底部操作栏 -->
<div class="action-bar">
    <el-button @click="handleCancel" class="action-btn btn-close">关闭</el-button>
    <el-button 
        v-if="!isEdit"  
        class="action-btn btn-save-add"  
        @click="handleSubmitAndContinue"
    >
        保存并新增
    </el-button>
    <el-button 
        class="action-btn btn-save" 
        type="primary"
        @click="handleSubmit"
    >
        保存
    </el-button>
</div>
</template>
<p></p>


<script>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import http from '../auth/index';
import * as XLSX from 'xlsx';

export default {
  setup() {
    const router = useRouter();
    const addFormRef = ref(null);
    const userOptions = ref([]);
    const departmentOptions = ref([]);
    // 初始化时清空库位数据
    const slotdata = ref([]); // 初始为空数组
const submitting = ref(false);

    // 分页配置
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    });

    // 获取当前用户信息
    const user = reactive({
      name: JSON.parse(sessionStorage.getItem("user"))?.name || '系统自动生成'
    });

    const addForm = reactive({
      is_default: 0,
      is_lock: 0,
      wh_code: '',
      wh_name: '',
      wh_address: '',
      wh_sort: null,
      wh_status: 0,
      wh_capacity: null,
      remark: '',
      wh_userId: null,
      wh_userName: '',
      wh_depId: null,
      wh_depName: '',
      wh_userPhone: '',
      create_name: user.name,
      create_time: new Date()
    });

    // 日期转换格式
    function formatDateTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }

    const rules = {
      wh_name: [{ required: true, message: '请输入仓库名称', trigger: 'blur' }],
      wh_userId: [{ required: true, message: '请选择仓库主管', trigger: 'change' }],
      wh_depId: [{ required: true, message: '请选择库管部门', trigger: 'change' }],
      wh_capacity: [{ required: true, message: '请输入仓库容量', trigger: 'blur' }]
    };

    // 库位表单验证规则
    const slotRules = reactive({
      slot_name: [{ required: true, message: '请输入库位名称', trigger: 'blur' }],
      slot_userId: [{ required: true, message: '请选择库位主管', trigger: 'change' }],
      slot_capacity: [{ required: true, message: '请输入库位容量', trigger: 'blur' }],
      slot_sort: [{ required: true, message: '请输入排序号', trigger: 'blur' }]
    });

    // 格式化状态
    const formatStatus = (row) => {
      return row.slot_status === 0 ? '启用' : '停用';
    };
  // 删除相关状态
const DeleteialogVisible = ref(false);
const busid = ref(null);
const selectedRows = ref([]);

// 显示删除对话框
const ShowDelete = (slot_code) => {
  busid.value = slot_code;
  DeleteialogVisible.value = true;
};



// 选中行变化时触发
const SelectChange = (selection) => {
  selectedRows.value = selection;
};


    // 查询库位数据
   const fetchSolst = async () => {
  try {
    const res = await http.get("/Slot/GetSlots", {
      params: {
        CurrentPage: pagination.currentPage,  // 注意参数名要匹配后端
        PageSize: pagination.pageSize        // 明确传递PageSize
      }
    });
    
    if (res.data && res.data.list) {
      slotdata.value = res.data.list;
      pagination.total = res.data.rows || 0;
    } else {
      slotdata.value = [];
      pagination.total = 0;
      ElMessage.warning('没有相关数据');
    }
  } catch (err) {
    console.error('获取数据失败:', err);
    ElMessage.error('获取数据失败');
    slotdata.value = [];
    pagination.total = 0;
  }
};


   // 单个删除，只能删除未保存的库位
const Delete = async () => {
  if (!busid.value) {
    ElMessage.error('未选择要删除的库位');
    return;
  }
  
  // 只能删除未保存的库位（这里busid.value实际上是slot_code）
  const slotToDelete = slotdata.value.find(slot => slot.slot_code === busid.value);
  if (!slotToDelete) {
    ElMessage.warning('未找到要删除的库位');
    return;
  }
  
  if (slotToDelete.slot_id !== null) {
    ElMessage.warning('只能删除未保存的库位');
    return;
  }
 
  try {
    // 从本地数据中删除
    slotdata.value = slotdata.value.filter(slot => slot.slot_code !== busid.value);
    ElMessage.success('删除成功');
    DeleteialogVisible.value = false;
    busid.value = null;
  } catch (err) {
    console.error('删除出错:', err);
    ElMessage.error('删除失败');
  }
};
 
// 批量删除，只能删除未保存的库位（slot_id为null的）
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的库位');
    return;
  }
 
  // 只能删除未保存的库位（slot_id为null的）
  const unsavedSlots = selectedRows.value.filter(slot => slot.slot_id === null);
  if (unsavedSlots.length === 0) {
    ElMessage.warning('只能删除未保存的库位');
    return;
  }
 
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${unsavedSlots.length} 个库位吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
 
    // 从本地数据中删除
    const slotCodesToDelete = unsavedSlots.map(slot => slot.slot_code);
    slotdata.value = slotdata.value.filter(slot => !slotCodesToDelete.includes(slot.slot_code));
 
    ElMessage.success(`成功删除 ${unsavedSlots.length} 个库位`);
  } catch (err) {
    if (err !== 'cancel') {
      console.error('批量删除出错:', err);
      ElMessage.error('操作中断');
    }
  }
};
// 导出功能，导出所有暂存的库位数据
const Export = () => {
  if (slotdata.value.length === 0) {
    ElMessage.warning('没有可导出的库位数据');
    return;
  }
 
  try {
    const wb = XLSX.utils.book_new();
    const excelData = slotdata.value.map((row) => ({
      "序号": row.slot_id || '未保存',
      "库位编号": row.slot_code,
      "库位名称": row.slot_name,
      "库位容量/m³": row.slot_capacity,
      "仓库主管": row.slot_userName,
      "排序": row.slot_sort,
      "库位状态": row.slot_status === 0 ? '启用' : '停用',
      "备注": row.remark,
    }));
 
    const ws = XLSX.utils.json_to_sheet(excelData);
    XLSX.utils.book_append_sheet(wb, ws, "库位信息");
    XLSX.writeFile(wb, `库位信息_${new Date().toISOString().slice(0, 10)}.xlsx`);
  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error('导出失败');
  }
};

    

  // 导入功能
const importLoading = ref(false);
const importUpload = ref(null);
 
const handleFileChange = async (file) => {
    if (!file?.raw) return;
    
    const isExcel = /\.(xlsx|xls)$/.test(file.name.toLowerCase());
    if (!isExcel) {
        ElMessage.warning('请上传Excel文件(.xlsx或.xls)');
        return;
    }
 
    importLoading.value = true;
    
    try {
        const formData = new FormData();
        formData.append('file', file.raw);
 
        const response = await http.post('/Slot/ImportSlots/ImportSlots', formData, { // 修改为正确的路由
            headers: { 'Content-Type': 'multipart/form-data' },
            timeout: 3600000
        });
 
        if (response.data.successCount > 0) {
            ElMessage.success(`成功导入 ${response.data.successCount} 条数据`);
        }
 
        if (response.data.errors?.length > 0) {
            // 显示前10条错误，避免过多
            const errorMessages = response.data.errors.slice(0, 10).join('\n');
            if (response.data.errors.length > 10) {
                errorMessages += `\n...还有 ${response.data.errors.length - 10} 条错误未显示`;
            }
            ElMessageBox.alert(errorMessages, '导入错误', {
                dangerouslyUseHTMLString: true,
                showConfirmButton: false,
                showClose: false,
                customClass: 'error-message-box'
            });
        }
 
        await fetchSolst(); // 刷新数据
    } catch (error) {
        let errorMsg = '导入失败';
        if (error.response) {
            errorMsg = error.response.data?.message || errorMsg;
        } else if (error.message) {
            errorMsg = error.message;
        }
        ElMessage.error(errorMsg);
    } finally {
        importLoading.value = false;
        if (importUpload.value) {
            importUpload.value.clearFiles();
        }
    }
};



     // 获取用户列表
    const fetchUser = async () => {
      try {
        const res = await http.get('/Slot/GetAllUsers');
        userOptions.value = res.data.map(item => ({
          user_id: item.user_id,
          user_name: item.user_name,
        }));
      } catch (error) {
        console.error('获取用户列表失败:', error);
        ElMessage.error('获取用户列表失败');
      }
    };

   
    // 获取部门列表
    const fetchDepartmentOptions = async () => {
      try {
        const res = await http.get('/Department/GetDepartments');
        departmentOptions.value = res.data.map(item => ({
          department_id: item.department_id,
          department_name: item.department_name
        }));
      } catch (error) {
        console.error('获取部门列表失败:', error);
        ElMessage.error('获取部门列表失败');
      }
    };

    // 部门选择变化时触发
    const handleDepartmentChange = (depId) => {
      const dept = departmentOptions.value.find(d => d.department_id === depId);
      addForm.wh_depName = dept?.department_name || '';
    };

    // 获取用户列表
    const fetchUserOptions = async () => {
      try {
        const res = await http.get('/Warehouse/GetAllUsers');
        userOptions.value = res.data.map(item => ({
          user_id: item.user_id,
          user_name: item.user_name,
          user_phone: item.user_phone || ''
        }));
      } catch (error) {
        console.error('获取用户列表失败:', error);
        ElMessage.error('获取用户列表失败');
      }
    };

    // 用户选择变化时触发
    const handleUserChange = async (userId) => {
      if (!userId) {
        addForm.wh_userName = '';
        addForm.wh_userPhone = '';
        return;
      }

      try {
        const selectedUser = userOptions.value.find(user => user.user_id === userId);

        if (selectedUser) {
          addForm.wh_userName = selectedUser.user_name;
          addForm.wh_userPhone = selectedUser.user_phone || '';

          if (!addForm.wh_userPhone) {
            const res = await http.get(`/Warehouse/GetPhoneByUserName?userName=${encodeURIComponent(selectedUser.user_name)}`);
            const phone = res.data?.data || '';
            addForm.wh_userPhone = phone;

            if (!phone) {
              ElMessage.warning('未找到有效的联系电话');
            }
          }
        }
      } catch (error) {
        console.error('获取联系电话失败:', error);
        ElMessage.error('获取联系电话失败');
        addForm.wh_userPhone = '';
      }
    };

       const handleCancel = () => {
      router.go(-1)
    };
 
    // 添加抽屉相关
    const drawer = ref(false);
    const addformref = ref(null);
    const addform = reactive({
  is_default: 0,
  is_lock: 0,
  wh_code: '',
  wh_name: '',
  wh_address: '',
  wh_sort: null,
  wh_status: 0,
  wh_capacity: null,
  remark: '',
  wh_userId: null,
  wh_userName: '',
  wh_depId: null,
  wh_depName: '',
  wh_userPhone: '',
  create_name: user.name,
  create_time: new Date(),
  slot_count: 0, // 添加库位数量字段
  wh_id: null,   // 添加仓库ID字段
  slot_status: 0 // 新增：库位状态默认启用
});
 
    // 暂存库位数组
    const tempSlots = ref([]);
    const isEdit = ref(false);
 
    // 添加库位（暂存）
const Add = async () => {
  try {
    const valid = await addformref.value.validate();
    if (!valid) return;
    
    // 生成库位编号
    const slotCode = await http.get("/CodeRule/GeneratedCode?id=17").then(res => res.data);
    
    // 获取选中的用户信息
    const selectedUser = userOptions.value.find(user => user.user_id === addform.slot_userId);
    
    // 添加到暂存数组
    slotdata.value.push({
      slot_id: null, // 明确设置为null，表示未保存到数据库
      slot_code: slotCode,
      slot_name: addform.slot_name,
      slot_capacity: addform.slot_capacity,
      slot_userId: addform.slot_userId,
      slot_userName: selectedUser?.user_name || '',
      slot_status: addform.slot_status,
      slot_sort: addform.slot_sort,
      remark: addform.remark,
    });
    
    ElMessage.success('库位已添加到暂存列表');
    drawer.value = false;
    addformref.value.resetFields();
    addform.slot_status = 0; // 新增：重置时也默认启用
  } catch (error) {
    console.error('添加失败:', error);
    ElMessage.error('添加失败');
  }
};

 
// 仓库添加 - 保存并返回列表
// 修改后的 handleSubmit 方法
const handleSubmit = async () => {
  if (submitting.value) return;
  submitting.value = true;
  
  try {
    // 1. 表单验证
    const valid = await addFormRef.value.validate().catch(() => {
      ElMessage.error('请填写完整的表单信息');
      return false;
    });
    if (!valid) return;

    // 2. 生成仓库编号
    let whCode = '';
    try {
      const response = await http.get("/CodeRule/GeneratedCode?id=3");
      whCode = response.data;
      if (!whCode) {
        throw new Error('仓库编号生成失败');
      }
    } catch (codeError) {
      console.error('生成仓库编号失败:', codeError);
      ElMessage.error('生成仓库编号失败，请重试');
      return;
    }

    // 3. 准备仓库数据
    const warehouseData = {
      wh_code: whCode,
      is_default: addForm.is_default ? 1 : 0,
      wh_name: addForm.wh_name.trim(),
      wh_capacity: Number(addForm.wh_capacity) || null,
      wh_depId: addForm.wh_depId,
      wh_depName: departmentOptions.value.find(d => d.department_id === addForm.wh_depId)?.department_name || '',
      wh_userId: addForm.wh_userId,
      wh_userName: userOptions.value.find(u => u.user_id === addForm.wh_userId)?.user_name || '',
      wh_userPhone: addForm.wh_userPhone,
      wh_address: addForm.wh_address,
      wh_sort: Number(addForm.wh_sort) || 0,
      wh_status: addForm.wh_status,
      is_lock: addForm.is_locked ? 1 : 0,
      remark: addForm.remark || "",
      create_name: user.name,
      create_time: formatDateTime(new Date()),
      wh_slot_num: slotdata.value.length
    };

    // 4. 保存仓库主数据
    let warehouseId;
    try {
      const warehouseResponse = await http.post('/Warehouse/AddWarehouse', warehouseData);
      warehouseId = warehouseResponse.data;
      if (!warehouseId) {
        throw new Error('仓库保存失败：未返回仓库ID');
      }
    } catch (warehouseError) {
      console.error('仓库保存失败:', warehouseError);
      throw new Error('仓库主数据保存失败');
    }

    // 5. 保存库位数据（如果有）
    if (slotdata.value?.length > 0) {
      try {
        const slotRequests = slotdata.value.map(slot => ({
          slot_code: slot.slot_code,
          slot_name: slot.slot_name,
          slot_capacity: Number(slot.slot_capacity),
          slot_userId: slot.slot_userId,
          slot_userName: slot.slot_userName,
          slot_status: slot.slot_status,
          slot_sort: Number(slot.slot_sort),
          remark: slot.remark,
          wh_id: warehouseId,
          create_name: user.name,
          create_time: formatDateTime(new Date()),
          is_delete: 0
        }));

        await http.post('/Slot/AddSlots/Batch', slotRequests);
      } catch (slotError) {
        console.error('库位保存过程中出错:', slotError);
        ElMessage.warning('库位数据保存失败，但仓库主数据已保存');
      }
    }

    // 6. 成功处理
    ElMessage.success('仓库保存成功');
    router.go(-1)
    
  } catch (error) {
    console.error('保存过程中出错:', error);
    ElMessage.error(error.message || '保存失败，请检查输入数据');
  } finally {
    submitting.value = false;
  }
};



// 仓库添加 - 保存并继续新增
const handleSubmitAndContinue = async () => {
    if (submitting.value) return;
  submitting.value = true;
  try {
    // 1. 表单验证
    const valid = await addFormRef.value.validate();
    if (!valid) return;
 
    // 2. 生成仓库编号
    let whCode = '';
    try {
      whCode = await http.get("/CodeRule/GeneratedCode?id=3").then(res => res.data);
      if (!whCode) {
        throw new Error('仓库编号生成失败');
      }
    } catch (codeError) {
      console.error('生成仓库编号失败:', codeError);
      ElMessage.error('生成仓库编号失败，请重试');
      return;
    }
 
    // 3. 准备仓库数据
    const warehouseData = {
      wh_code: whCode,
      is_default: addForm.is_default ? 1 : 0,
      wh_name: addForm.wh_name.trim(),
      wh_capacity: Number(addForm.wh_capacity) || null,
      wh_depId: addForm.wh_depId,
      wh_depName: departmentOptions.value.find(d => d.department_id === addForm.wh_depId)?.department_name || '',
      wh_userId: addForm.wh_userId,
      wh_userName: userOptions.value.find(u => u.user_id === addForm.wh_userId)?.user_name || '',
      wh_userPhone: addForm.wh_userPhone,
      wh_address: addForm.wh_address,
      wh_sort: Number(addForm.wh_sort) || 0,
      wh_status: addForm.wh_status,
      is_lock: addForm.is_locked ? 1 : 0,
      remark: addForm.remark || "",
      create_name: user.name,
      create_time: formatDateTime(new Date()),
      wh_slot_num: slotdata.value.length
    };
 
    // 4. 保存仓库主数据
    let warehouseId;
    try {
      const warehouseResponse = await http.post('/Warehouse/AddWarehouse', warehouseData);
      warehouseId = warehouseResponse.data;
      if (!warehouseId) {
        throw new Error('仓库保存失败：未返回仓库ID');
      }
    } catch (warehouseError) {
      console.error('仓库保存失败:', warehouseError);
      throw new Error('仓库主数据保存失败');
    }
 
    // 5. 保存库位数据（如果有）
    if (slotdata.value?.length > 0) {
      try {
        const slotRequests = slotdata.value.map(slot => ({
          slot_code: slot.slot_code,
          slot_name: slot.slot_name,
          slot_capacity: Number(slot.slot_capacity),
          slot_userId: slot.slot_userId,
          slot_userName: slot.slot_userName,
          slot_status: slot.slot_status,
          slot_sort: Number(slot.slot_sort),
          remark: slot.remark,
          wh_id: warehouseId,
          create_name: user.name,
          create_time: formatDateTime(new Date()),
          is_delete: 0
        }));
 
        await http.post('/Slot/AddSlots/Batch', slotRequests);
      } catch (slotError) {
        console.error('库位保存过程中出错:', slotError);
        ElMessage.warning('库位数据保存失败，但仓库主数据已保存');
      }
    }
 
    // 6. 成功处理 - 重置表单并保留在当前页
    ElMessage.success('仓库保存成功');
    resetForm(); // 重置表单
    slotdata.value = []; // 清空库位数据
    // 重新生成新的仓库编号以便继续添加
    try {
      const newWhCode = await http.get("/CodeRule/GeneratedCode?id=3").then(res => res.data);
      if (newWhCode) {
        addForm.wh_code = newWhCode;
      }
    } catch (error) {
      console.error('生成新仓库编号失败:', error);
      // 即使失败也不影响继续使用，只是编号不会自动生成
    }
    
  } catch (error) {
    console.error('保存过程中出错:', error);
    ElMessage.error(error.message || '保存失败');
  }
};

    const resetForm = () => {
      Object.assign(addForm, {
        is_default: 0,
        is_lock: 0,
        wh_code: '',
        wh_name: '',
        wh_address: '',
        wh_sort: null,
        wh_status: 0,
        wh_capacity: null,
        remark: '',
        wh_userId: null,
        wh_userName: '',
        wh_depId: null,
        wh_depName: '',
        wh_userPhone: '',
        create_name: user.name,
        create_time: new Date()
      });
    };
         

    // 处理分页变化
    const handlePageChange = (page) => {
      pagination.currentPage = page;
      fetchSolst();
    };

    const editDrawer = ref(false);
    const editFormRef = ref(null);
    const editForm = reactive({
      slot_id: null,
      slot_code: "",
      slot_name: "",
      slot_capacity: null,
      slot_userId: null,
      slot_status: 0,
      slot_sort: null,
      remark: ""
    });
 

// 显示编辑抽屉
    const showEditDrawer = (row) => {
      editForm.slot_id = row.slot_id;
      editForm.slot_code = row.slot_code;
      editForm.slot_name = row.slot_name;
      editForm.slot_capacity = row.slot_capacity;
      editForm.slot_userId = row.slot_userId;
      editForm.slot_status = row.slot_status;
      editForm.slot_sort = row.slot_sort;
      editForm.remark = row.remark;
      editDrawer.value = true;
    };
 
// 更新库位
const Update = async () => {
  try {
    const valid = await editFormRef.value.validate();
    if (!valid) return;
 
    // 获取选中的用户信息
    const selectedUser = userOptions.value.find(user => user.user_id === editForm.slot_userId);
    
    if (!selectedUser) {
      ElMessage.error('请选择有效的库位主管');
      return;
    }
 
    // 构建请求数据
    const postData = {
      slot_id: editForm.slot_id,
      slot_code: editForm.slot_code,
      slot_name: editForm.slot_name,
      slot_capacity: editForm.slot_capacity,
      slot_userId: editForm.slot_userId,
      slot_userName: selectedUser.user_name,
      slot_status: editForm.slot_status,
      slot_sort: editForm.slot_sort,
      remark: editForm.remark,
    };
 
    console.log('提交的数据:', postData); // 调试用
 
    const submitRes = await http.put('/Slot/UpdateSlot', postData);
 
    if (submitRes.data > 0) {
      ElMessage.success('更新成功');
      editDrawer.value = false;
      await fetchSolst(); // 刷新数据
      editFormRef.value.resetFields();
    } else {
      ElMessage.error('更新失败');
    }
  } catch (error) {
    console.error('更新出错:', error);
    ElMessage.error('更新失败');
  }
};


    onMounted(async () => {
      await fetchUserOptions();
      await fetchDepartmentOptions();
      // await fetchSolst(); // 确保在组件挂载时获取库位数据
    });

    return {
      addFormRef,
      addForm,
      rules,
      handleSubmitAndContinue,
      tempSlots,
      handleFileChange,
      importUpload,
      userOptions,
      departmentOptions,
      slotdata,
      pagination,
      formatStatus,
      handleUserChange,
      handleDepartmentChange,
      handleCancel,
      isEdit,
      handleSubmit,
      handlePageChange,
      Export,
      Add,
      drawer,
      addformref,
      addform,
      slotRules,
      fetchUser,
      Update,
      editDrawer,
      editFormRef,
      editForm,
      showEditDrawer,
      ShowDelete,
      Delete,
      selectedRows,
      DeleteialogVisible,
      busid,
      SelectChange,
      handleBatchDelete
    };
  }
};
</script>
 

<style scoped>
.warehouse-add-container {
  padding: 20px;
}
.location-table-container {
  padding: 20px;
}
/* 卡片标题左对齐样式 */
.card-header-title {
  display: block;
  text-align: left;
  width: 100%;
  font-weight: bold;
}
/* 抽屉表单样式调整 */
.el-drawer__body {
  padding: 20px;
}
 
.el-form-item {
  margin-bottom: 18px;
}
 
.el-input, .el-select {
  width: 100%;
}
 
.el-radio-group {
  display: flex;
  gap: 20px;
}
 
/* 调整表单标签左对齐 */
.el-form--label-left .el-form-item__label {
  text-align: left;
}

/* 错误消息框样式 */
.error-message-box {
    max-width: 800px;
    white-space: pre-line;
}

.error-message-box .el-message-box__content {
    max-height: 400px;
    overflow-y: auto;
}

/* 表格样式 */
.el-table {
  margin-top: 10px;
}
/* 基础信息卡片样式 */
.base-info-card {
  width: 80%; /* 占页面的1/3宽度 */
  margin-left: -20px; /* 向左移动20px */
  border-radius: 10px; /* 添加圆角 */
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); /* 可选：增强阴影效果 */
}
    /* 底部操作栏自适应 */
    .action-bar {
        position: fixed;
        bottom: 0;
        right: 0.5%; /* 与表单右侧对齐 */
        left: 210px; /* 与菜单栏宽度一致 */
        background: white;
        border-top: 1px solid #e6e6e6;
        padding: 15px;
        text-align: right;
    }

    .action-btn {
        border: none;
        padding: 8px 20px;
        border-radius: 4px;
        cursor: pointer;
        margin-left: 10px;
    }
    .btn-close {
        background: #f4f4f5;
        color: #666;
    }
    .btn-save {
        background: #3a7bd5;
        color: white;
    }
    .btn-save-add {
        background: #38c172;
        color: white;
    }
</style>